package com.yuedong.down;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.widget.Toast;


import com.yuedong.down.util.UriUtil;

import java.io.File;

/**
 * 下载服务类
 */
public class DownloadService extends Service {

    private DownloadTask downloadTask;
    private String downloadUrl;
    private int notifyLogo = 0;
    private int id=10;
    public void setProgressCallBack(ProgressCallBack progressCallBack) {
        this.progressCallBack = progressCallBack;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel mChannel = null;
            mChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), channelId).build();
            startForeground(id, notification);
        }
    }

    private ProgressCallBack progressCallBack;
    private DownloadListener listener = new DownloadListener() {

        @Override
        public void onProgress(int progress) {
            if (progressCallBack != null) progressCallBack.onProgress(progress);
            getNotificationManager().notify(id, getNotification(getString(R.string.downloading), progress));
        }

        @Override
        public void onSuccess(File file) {
            if (progressCallBack != null) progressCallBack.onProgress(100);
            install(file);
            downloadTask = null;
            stopForeground(true);
            getNotificationManager().notify(id, getNotification(getString(R.string.download_sucess), -1));
            Toast.makeText(DownloadService.this, "下载成功", Toast.LENGTH_SHORT).show();
        }

        private void install(File file) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri contentUri = UriUtil.getFileUri(DownLoadApplication.getmContext(), file);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            startActivity(intent);


        }

        /**
         *用户下载失败
         */
        @Override
        public void onFailed() {
            downloadTask = null;
            stopForeground(true);
//            getNotificationManager().notify(1, getNotification("下载失败", -1));
////            Toast.makeText(DownloadService.this, "下载失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            downloadTask = null;
            stopForeground(true);
            //  Toast.makeText(DownloadService.this, "下载已暂停", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            downloadTask = null;
            stopForeground(true);
            Toast.makeText(DownloadService.this, getString(R.string.download_has_cancle), Toast.LENGTH_SHORT).show();
        }
    };

    private DownloadBinder mBinder = new DownloadBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private boolean isDownLoading;

    public class DownloadBinder extends Binder {
        public DownloadService getDownLoadService() {
            return DownloadService.this;
        }

        public boolean isDownLoading() {
            return isDownLoading;
        }

        public void startDownload(String url) {
            if (downloadTask == null) {
                downloadUrl = url;
                downloadTask = new DownloadTask(listener);
                //启动下载任务
                downloadTask.execute(downloadUrl);
                isDownLoading = true;
                startForeground(id, getNotification(getString(R.string.downloading), 0));
            }
        }

        public void pauseDownload() {
            if (downloadTask != null) {
                downloadTask.pauseDownload();
            }
        }


        public void cancelDownload() {
            if (downloadTask != null) {
                isDownLoading = false;
                downloadTask.cancelDownload();
            } else {
                if (downloadUrl != null) {
                    //取消下载时将文件删除，并将通知关闭
                    String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                    File file = new File(directory + fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    getNotificationManager().cancel(id);
                    stopForeground(true);
                }
            }

        }


    }

    private NotificationManager notificationManager;
    /**
     * 高版本需要设置渠道号方可显示通知
     */
    private String channelId = "downloadid" + DownLoadApplication.getmContext().getPackageName();
    private String channelName = "downloadName" + DownLoadApplication.getmContext().getPackageName();

    private NotificationManager getNotificationManager() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
                if (notificationManager != null) {
                    notificationManager.createNotificationChannel(channel);
                }
            }
        }
        return notificationManager;
    }

    public void setNotifyLogo(int logoRes) {
        this.notifyLogo = logoRes;
    }

    Notification notification;

    private Notification getNotification(String title, int progress) {


        Intent intent = new Intent();
        //PendingIntent是等待的Intent,这是跳转到一个Activity组件。当用户点击通知时，会跳转到MainActivity
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

       // NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
      Notification.Builder builder=new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  builder.setChannelId(channelId);}
        //设置通知的小图标
        if(notifyLogo!=0)builder.setSmallIcon(notifyLogo != 0 ? notifyLogo : R.mipmap.logo);
        //设置通知的大图标，当下拉系统状态栏时，就可以看到设置的大图标
        if(notifyLogo!=0)  builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), notifyLogo != 0 ? notifyLogo : R.mipmap.logo));
        //当通知被点击的时候，跳转到MainActivity中
        builder.setContentIntent(pi);
        //设置通知的标题
        builder.setContentTitle(title);
        builder.setOnlyAlertOnce(true);
        builder.setSound(null);
        if (progress > 0) {
            //当progress大于或等于0时，才需要显示下载进度
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        notification = builder.getNotification();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        return notification;
    }

    public interface ProgressCallBack {
        void onProgress(int pro);
    }
}
